import React, {useEffect, useState} from 'react'
import styles from './Check.module.scss'
import type {RadioChangeEvent} from 'antd'
import {Button, Divider, Input, message, Radio, Row, Space, Table} from 'antd'
import {CheckOutlined, CloseOutlined, SearchOutlined} from '@ant-design/icons'
import {useSelector} from 'react-redux'
import type {RootState} from '../../store'
import {useAppDispatch} from '../../store'
import _ from 'lodash'
import type {ColumnsType} from 'antd/es/table'
import {getApplyAction, Infos, putApplyAction, updateCheckList} from '../../store/modules/checks'
import {Info, putRemindAction, updateInfo} from "../../store/modules/news";


const approverTypes = [
    {label: '全部', value: '全部'},
    {label: '待审批', value: '待审批'},
    {label: '已通过', value: '已通过'},
    {label: '未通过', value: '未通过'},
]
const defaultType = approverTypes[0].value

export default function Check() {
    const columns: ColumnsType<Infos> = [
        {
            title: '申请人',
            dataIndex: 'applicantname',
            key: 'applicantname',
            width: 180
        },
        {
            title: '审批事由',
            dataIndex: 'reason',
            key: 'reason',
            width: 180
        },
        {
            title: '时间',
            dataIndex: 'time',
            key: 'time',
            render(_) {
                return _.join(' - ')
            }
        },
        {
            title: '备注',
            dataIndex: 'note',
            key: 'note',
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            width: 180,
            render(_, record) {
                return (
                    <Space>
                        <Button type="primary" shape="circle" size="small" icon={<CheckOutlined/>}
                                style={{backgroundColor: '#67c23a', border: '1px #67c23a solid'}}
                                onClick={handlePutApply(record._id as string, '已通过', record.applicantid as string)}/>
                        <Button type="primary" danger shape="circle" size="small" icon={<CloseOutlined/>}
                                onClick={handlePutApply(record._id as string, '未通过', record.applicantid as string)}/>
                    </Space>
                )
            }
        },
        {
            title: '状态',
            dataIndex: 'state',
            key: 'state',
            width: 180
        }
    ];
    const dispatch = useAppDispatch()
    const [searchWord, setSearchWord] = useState('')
    const [approverType, setApproverType] = useState(defaultType)
    const usersInfos = useSelector((state: RootState) => state.users.infos)
    const checkList = useSelector((state: RootState) => state.checks.checkList).filter((item) => {
        console.log((item.state === approverType || defaultType === approverType) && (item.note as string).includes(searchWord));
        return (item.state === approverType || defaultType === approverType) && (item.note as string).includes(searchWord)
    })
    const newsInfo = useSelector((state: RootState) => state.news.info)

    const handlePutApply = (_id: string, state: '已通过' | '未通过', applicantid: string) => {
        return () => {
            dispatch(putApplyAction({_id, state})).then((action) => {
                const {errcode} = (
                    action.payload as { [index: string]: unknown }
                ).data as { [index: string]: unknown }
                if (errcode === 0) {
                    message.success('审批成功');
                    dispatch(getApplyAction({approverid: usersInfos._id as string})).then(
                        (action) => {
                            const {errcode, rets} = (
                                action.payload as { [index: string]: unknown }
                            ).data as { [index: string]: unknown }
                            if (errcode === 0) {
                                dispatch(updateCheckList(rets as Infos[]))
                            }
                        }
                    )
                    dispatch(putRemindAction({userid: applicantid, applicant: true}))
                }
            })
        }
    }
    useEffect(() => {
        if (newsInfo.approver) {
            dispatch(putRemindAction({userid: usersInfos._id as string, approver: false})).then((action) => {
                const {errcode, info} = (action.payload as { [index: string]: unknown }).data as {
                    [index: string]: unknown
                }
                if (errcode === 0) {
                    dispatch(updateInfo(info as Info))
                }
            })
        }
    }, [dispatch, usersInfos, newsInfo])
    useEffect(() => {
        if (_.isEmpty(checkList)) {
            dispatch(getApplyAction({approverid: usersInfos._id as string})).then(
                (action) => {
                    const {errcode, rets} = (
                        action.payload as { [index: string]: unknown }
                    ).data as { [index: string]: unknown }
                    if (errcode === 0) {
                        dispatch(updateCheckList(rets as Infos[]))
                    }
                }
            )
        }
    }, [checkList, usersInfos, dispatch])
    const searchWordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setSearchWord(e.target.value)
    }
    return (
        <div>
            <Row className={styles['check-title']} justify='end'>
                <Space>
                    <Input placeholder='请输入搜索关键词' prefix={<SearchOutlined/>} onChange={searchWordChange}/>
                    <Button type='primary' icon={<SearchOutlined/>}>
                        搜索
                    </Button>
                    <Divider type={'vertical'} style={{borderLeftColor: '#dcdfe6'}}></Divider>
                    <Radio.Group
                        value={approverType}
                        options={approverTypes}
                        optionType='button'
                        buttonStyle='solid'
                        onChange={(e: RadioChangeEvent) => setApproverType(e.target.value)}
                    />
                </Space>
            </Row>
            <Table
                rowKey="_id"
                pagination={{defaultPageSize: 5}}
                bordered
                size={'small'}
                className={styles['check-title']}
                dataSource={checkList}
                columns={columns}
            />
        </div>
    )
}